/**
 * Mobius-style Background Shader Component
 * Requirements: 1.1
 */

import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import { Mesh, ShaderMaterial } from 'three';

/**
 * Mobius-style background with animated shader
 * Creates a surreal, geometric twisted aesthetic
 */
export function MobiusBackground() {
  const meshRef = useRef<Mesh>(null);
  const materialRef = useRef<ShaderMaterial>(null);

  // Vertex shader - defines the geometry transformation
  const vertexShader = `
    varying vec2 vUv;
    varying vec3 vPosition;
    
    void main() {
      vUv = uv;
      vPosition = position;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `;

  // Fragment shader - defines the color and visual effects
  const fragmentShader = `
    uniform float uTime;
    varying vec2 vUv;
    varying vec3 vPosition;
    
    // Mobius-inspired color gradient with geometric patterns
    vec3 mobiusGradient(vec2 uv, float time) {
      // Create twisted coordinate system
      float angle = atan(uv.y - 0.5, uv.x - 0.5);
      float radius = length(uv - 0.5);
      
      // Mobius twist effect
      float twist = sin(angle * 3.0 + time * 0.5) * cos(radius * 5.0 - time * 0.3);
      
      // Color palette inspired by surreal geometry
      vec3 color1 = vec3(0.2, 0.1, 0.4); // Deep purple
      vec3 color2 = vec3(0.1, 0.3, 0.6); // Blue
      vec3 color3 = vec3(0.4, 0.2, 0.5); // Violet
      
      // Mix colors based on twisted coordinates
      float mixFactor = (twist + 1.0) * 0.5;
      vec3 color = mix(color1, color2, mixFactor);
      color = mix(color, color3, sin(time * 0.2 + radius * 2.0) * 0.5 + 0.5);
      
      return color;
    }
    
    void main() {
      vec3 color = mobiusGradient(vUv, uTime);
      
      // Add subtle noise for texture
      float noise = fract(sin(dot(vUv, vec2(12.9898, 78.233)) + uTime * 0.1) * 43758.5453);
      color += noise * 0.05;
      
      gl_FragColor = vec4(color, 1.0);
    }
  `;

  // Animate the shader over time
  useFrame((state) => {
    if (materialRef.current) {
      materialRef.current.uniforms.uTime.value = state.clock.elapsedTime;
    }
  });

  return (
    <mesh ref={meshRef} position={[0, 0, -20]} scale={[50, 50, 1]}>
      <planeGeometry args={[1, 1, 32, 32]} />
      <shaderMaterial
        ref={materialRef}
        vertexShader={vertexShader}
        fragmentShader={fragmentShader}
        uniforms={{
          uTime: { value: 0 }
        }}
      />
    </mesh>
  );
}
